## Filters added to this controller apply to all controllers in the application.
## Likewise, all the methods added will be available for all controllers.
#
#class ApplicationController < ActionController::Base
#  helper :all # include all helpers, all the time
#  protect_from_forgery # See ActionController::RequestForgeryProtection for details
#
#  # Scrub sensitive parameters from your log
#  # filter_parameter_logging :password
#end

class ApplicationController < ActionController::Base
  # Pick a unique cookie name to distinguish our session data from others'
  #session :session_key => '_dloc_elearning_session_id'
  helper_method :to_date, :songrit, :current_user, :qtype_name, :category_name, :blog_owner?,
    :thai_num
  before_filter :chat_user_leave

  require "base64"
  require "key"
  require "open-uri"
  require "digest/sha1"

  def thai_num(s)
    a= s.clone
    a.gsub!('0', '๐'.mb_chars)
    a.gsub!('1', '๑'.mb_chars)
    a.gsub!('2', '๒'.mb_chars)
    a.gsub!('3', '๓'.mb_chars)
    a.gsub!('4', '๔'.mb_chars)
    a.gsub!('5', '๕'.mb_chars)
    a.gsub!('6', '๖'.mb_chars)
    a.gsub!('7', '๗'.mb_chars)
    a.gsub!('8', '๘'.mb_chars)
    a.gsub!('9', '๙'.mb_chars)
    return a
  end
  def tis620(t)
    cd = Iconv.new("TIS-620", "UTF-8")
    cd.iconv(t)
  end
  def to_date(t)
    Date.parse(t.strftime('%Y/%m/%d'))
  end
  def utf8(t)
    cd = Iconv.new("UTF-8", "TIS-620")
    cd.iconv(t)
  end
  def blog_owner?
    return false unless session[:user_id]
    return true unless params[:user]
    current_user.login == params[:user]
  end
  def category_name(id)
    case id
    when 0
      "pre-test"
    else
      "post-test"
    end
  end
  def qtype_name(qtype)
    case qtype
    when 0
      "ถูกหรือผิด"
#      "✔✖"
    when 1
      "ปรนัย"
    end
  end
#  def auth_admin
#    role = session[:user] ? session[:user][:role] : ''
#    redirect_to '/' unless role.include?('A')
#  end
  def admin?
    role = session[:user_id] ? current_user.role : ''
    role ||= ''
    redirect_to_root unless role.include?('A')
  end
  def isadmin?
    role = session[:user_id] ? current_user.role : ''
    role ||= ''
    role.include?('A')
  end
  #check if now > 60 days since user sign up so he can take exam
  def day60?
    if isadmin?
      return true
    elsif (Date.today-to_date(current_user.created_at)) < 60
      flash[:notice] = "ผู้ประสงค์จะทำแบบทดสอบต้องลงทะเบียนมาแล้วไม่น้อยกว่า 60 วัน"
      redirect_to "/"
    end
  end
  def date15?
#    if isadmin?
#      return true
#    elsif Date.today.day!=15
#      flash[:notice] = "แบบทดสอบเข้าใช้งานได้เฉพาะวันเวลาที่กำหนดเท่านั้น"
#      redirect_to "/"
#    end
    return true
  end
  def check_admin?
    role = session[:user_id] ? current_user.role : ''
    role ||= ''
#    redirect_to_root unless role.include?('A')
    role.include?('A')
  end
  def login?
    unless session[:user_id]
      flash[:notice] = "กรุณาล็อกอินก่อนเข้าใช้งาน"
      redirect_to_root
    end
  end
  def chat_user_leave
    return unless session[:user_id]
    return if params[:controller]=="chat"
    chat_user= ChatUser.find_by_login current_user.login
    if chat_user
#      Juggernaut.send_to_all("$('#{chat_user.login}').remove()") unless DLOC_SERVER
      chat_user.destroy
    end
  end
  def broadcast(s)
    user= "<span class=user>#{@login}</span>"
    Juggernaut.send_to_all("$('main').appendText('#{user}: #{s}')")
  end
  def announce_user(u)
    user= User.find_by_login u
    tag= %Q(<div title= '#{user.title}#{user.fname} #{user.lname}' id='#{user.login}'>)
    tag += "<img src=/images/user.png /> #{u}"
    Juggernaut.send_to_all( %Q($('users').appendText("#{tag}") ) )
  end
  def win32?
    !(RUBY_PLATFORM =~ /win32/).nil?
  end
  def current_user
    return nil unless session[:user_id]
    User.find session[:user_id]
  end
  def redirect_to_root
    redirect_to root_path
  end
  def root_path
    root+"/"
  end
  def root
    ENV['RAILS_RELATIVE_URL_ROOT'] || ""
  end
  def old_save_file(file_params)
    file_url = file_params.original_filename
    save_path = "#{RAILS_ROOT}/public/files"
    FileUtils.makedirs(save_path) if !File.exist?(save_path)
    file_name = file_url.gsub("\\","/").split("/").last
    split_file_name_and_type = file_name.split(".")
    if split_file_name_and_type.length < 2
      return
    end
    file_name = split_file_name_and_type[0]+Time.now.strftime('%y%m%d%H%M%S')+'.'+split_file_name_and_type.last
    target_path = File.join(save_path,file_name)
    f = File.new(target_path, "wb")
    f.write file_params.read
    f.close
    file_name
  end
  def save_file(file_params)
    file_url = file_params.original_filename
    save_path = "#{RAILS_ROOT}/public/materials"
    FileUtils.makedirs(save_path) if !File.exist?(save_path)
    file_name = file_url.gsub("\\","/").split("/").last
    split_file_name_and_type = file_name.split(".")
    if split_file_name_and_type.length < 2
      return
    end
    file_name = split_file_name_and_type[0]+Time.now.strftime('%y%m%d%H%M%S')+'.'+split_file_name_and_type.last
    target_path = File.join(save_path,file_name)
    f = File.new(target_path, "wb")
    f.write file_params.read
    f.close
    file_name
  end
  def post_log
    applog = AppLog.new :controller=>params[:controller], :action=>params[:action],
      :params=>params, :session=>session, :ip=>request.env['REMOTE_ADDR']
#    applog.course_id= params[:id] if applog.controller=='course' && applog.action=='download'
     applog.course_id= Material.find(params[:id]).course_id if applog.controller=='course' && applog.action=='download'
#    applog.user_id = session[:user].id if session[:user]
    applog.user_id = session[:user_id] if session[:user_id]
    applog.session_id = request.session_options[:id] if session[:user_id]
    # applog.session_id= session.session_id
    applog.save
  end
  def songrit(key)
    session[:songrit]= {} unless session[:songrit]
    session[:songrit][key] ||= Songrit.find_by_code(key.to_s).value
  end
  def authenticate
    return true if params[:login]
    if session[:user_id]
      return true
    else
      flash[:notice]= "กรุณาล็อกอินเพื่อเข้าใช้บริการ"
      redirect_to_root
    end
  end
  def authenticate_false
    if session[:user_id]
      return true
    else
      session[:user_id]= 1
    end
  end
  def authenticate_tcid
    if session[:user_id]
      return true
    else
      redirect_to "#{songrit(:host_sso)}?callback=#{songrit(:host)}/main/login_tcid&app=#{songrit(:tcid_appid)}"
    end
  end
  def http(urlword)
    if win32?
      Net::HTTP.get(URI(urlword))
    else
      require "net/http"
      proxy_host= "172.16.0.5"
      proxy_port = 8080
      url = URI.parse(urlword)
#      return url.path
#      req = Net::HTTP::Get.new(url.path+'?'+url.query)
      req = Net::HTTP::Get.new(urlword)
      res = nil
      res = Net::HTTP::Proxy(proxy_host,proxy_port).start(url.host, url.port) do |http|
        http.request(req)
      end
      @word = res.body
    end
  end
  def http0(url)
    if win32?
      Net::HTTP.get(URI(url))
    else
      phost= "172.16.0.5"
      pport = "8080"
      Net::HTTP::Proxy(phost, pport.to_i).get(URI(url))
    end
  end
end

class Object
  def songrit(key)
    Songrit.find_by_code(key.to_s).value
  end
end
